package cn.com.dhc.danlu.activity.terminal;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yiji.www.frameworks.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.myself.AddressListActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.StoreTypeListViewAdapter;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.request.login.LoginRequest;
import cn.com.hd.mall.web.webservices.entity.request.regist.TerminalRequest;
import cn.com.hd.mall.web.webservices.entity.response.model.ResultModel;
import cn.com.hd.mall.web.webservices.entity.response.regist.ShopTypeListResponse;
import cn.com.hd.mall.web.webservices.entity.response.regist.ShopTypeListResponse.ShopTypeCode;
import cn.com.hd.mall.web.webservices.entity.response.regist.TerminalInformationModifyResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author: 李一方
 * @time: 2016-08-30 14:55
 * @mail: liyifang@danlu.com
 * @desc: 修改审批信息界面
 */
public class ModifyTerminalInfoActivity extends BaseActivity implements View.OnClickListener {
    private TextView tvPhone;
    private TextView tvAccount;
    private TextView tvShopType;
    private TextView tvShopAddress;
    private EditText etShopName;
    private EditText etBusinessLicense;
    private EditText etShopDetail;
    private ImageView ivBack;
    private Button btnResubmit;
    private ViewDialog dialog;
    private ViewDialog.Builder builder;
    private String address;
    private String shopTypeName;
    private List<String> shopNames;
    private List<ShopTypeCode> shopCodes;
    private TerminalRequest request;
    // private DanluTaskProxy danluTaskProxy;
    private LoginRequest loginRequest;

    //    private DanluTaskListener onModifyInfoListener = new DanluTaskListener<ModifyDeliverAddressRequest, Void, ResultModel>() {
    //
    //        @Override
    //        public void taskSuccess(ResultModel resultModel) {
    //            if (null != resultModel) {
    //                TerminalInformationModifyResponse result = (TerminalInformationModifyResponse) resultModel.getModel();
    //                if (result.getSuccess().equals("0")) {
    //                    toPrevious();
    //                } else {
    //                    String res = result.getCheckResult();
    //                    ToastUtils.showShort(ModifyTerminalInfoActivity.this, !TextUtils.isEmpty(res) ? res : "修改失败");
    //                }
    //            }
    //        }
    //
    //        @Override
    //        public void taskError(ResultModel resultModel, int resStringId) {
    //            if (resultModel == null) {
    //                ToastUtils.showShort(ModifyTerminalInfoActivity.this, R.string.webservices_access_error);
    //            } else {
    //                ToastUtil.getInstance().show(resStringId);
    //            }
    //        }
    //    };

    /**
     * 前往上一界面
     */
    private void toPrevious() {
        Intent intent = new Intent(ModifyTerminalInfoActivity.this, TerminalProgressActivity.class);
        intent.putExtra("loginname", loginRequest.getUsername());
        intent.putExtra("password", loginRequest.getPassword());
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        toPrevious();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 100:
                tvShopAddress.setText(data.getStringExtra("ADDR"));
                request.setTerminalAreaCode(data.getStringExtra("DCODE"));
                break;

            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_terminal_info);

        initArgs();
        initViews();
        setupViews();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    private void initArgs() {
        address = getIntent().getStringExtra("address");
        shopTypeName = getIntent().getStringExtra("shopTypeName");
        request = (TerminalRequest) getIntent().getSerializableExtra("data");
        loginRequest = (LoginRequest) getIntent().getSerializableExtra("loginData");
    }

    private void initViews() {
        //        delegate.setContentView(R.layout.activity_modify_terminal_info, R.terminal_info.class);

        tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvAccount = (TextView) findViewById(R.id.tv_account);
        tvShopType = (TextView) findViewById(R.id.tv_shop_type);
        tvShopAddress = (TextView) findViewById(R.id.tv_shop_address);
        etShopName = (EditText) findViewById(R.id.et_shop_name);
        etBusinessLicense = (EditText) findViewById(R.id.et_business_license);
        etShopDetail = (EditText) findViewById(R.id.et_shop_detail);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        btnResubmit = (Button) findViewById(R.id.btn_resubmit);
    }

    private void setupViews() {
        ivBack.setOnClickListener(this);
        tvShopType.setOnClickListener(this);
        tvShopAddress.setOnClickListener(this);
        btnResubmit.setOnClickListener(this);

        tvPhone.setText(getIntent().getStringExtra("phone"));
        tvAccount.setText(getIntent().getStringExtra("username"));
        tvShopType.setText(shopTypeName);
        tvShopAddress.setText(address);

        etShopName.setText(request.getTerminalName());
        etShopDetail.setText(request.getTerminalDetailAddress());
        etBusinessLicense.setText(request.getBusinessLicenseCode());

        CommonUtils.showSoftInputFromWindow(ModifyTerminalInfoActivity.this, etShopName);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                toPrevious();
                break;

            case R.id.btn_resubmit:
                checkForm();
                break;

            case R.id.tv_shop_type:
                tvShopType.setClickable(false);
                if (shopNames == null || shopNames.size() <= 0) {
                    BaseRequest form = new BaseRequest();
                    shopNames = new ArrayList<>();
                    agent.getApi()
                            .getStoreTypeList(form)
                            .compose(OperatorUtils.<ShopTypeListResponse>defaultSchedulers())
                            .subscribe(new GeneralBusinessObserver<ShopTypeListResponse>() {
                                @Override
                                protected void onSuccess(ShopTypeListResponse model) {
                                    if (null != model.getShopList()) {
                                        shopCodes = model.getShopList();
                                        for (int i = 0; i < model.getShopList().size(); i++) {
                                            shopNames.add(shopCodes.get(i).getCodeValue());

                                        }
                                        chooseShopType(shopNames);
                                    }
                                }

                                @Override
                                protected void onAlertTips(String displayMessage) {
                                    ToastUtil.getInstance().show(displayMessage);
                                }
                            });
                } else {
                    chooseShopType(shopNames);
                }
                break;

            case R.id.tv_shop_address:
                Intent intent = new Intent();
                intent.putExtra("REGISTER", "register");
                intent.setClass(ModifyTerminalInfoActivity.this, AddressListActivity.class);
                startActivityForResult(intent, 100);
                break;

            default:
                break;
        }
    }

    /**
     * 获取商店类型
     */
    private void getStoreType(ResultModel result) {
        ShopTypeListResponse response = (ShopTypeListResponse) result.getModel();
        if (response != null && response.getShopList() != null && response.getShopList().size() > 0) {
            shopCodes = response.getShopList();
            for (int i = 0; i < response.getShopList().size(); i++) {
                shopNames.add(shopCodes.get(i).getCodeValue());

            }
            chooseShopType(shopNames);
        }
    }

    /**
     * 选择商店类型
     *
     * @param shopNames 商店类型名称
     */
    private void chooseShopType(final List<String> shopNames) {
        // 创建Builder
        if (builder == null) {
            //            builder = new ViewDialog.Builder(getDelegate().getContext());
            builder = new ViewDialog.Builder(ModifyTerminalInfoActivity.this);
        }

        // 设置自定义的View
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(this).inflate(R.layout.layout_store_type_list, null);
        final ListView listview = (ListView) view.findViewById(R.id.store_type_list);
        //        StoreTypeListViewAdapter adapters = new StoreTypeListViewAdapter(getDelegate().getContext(), (ArrayList<String>) shopNames);
        StoreTypeListViewAdapter adapters = new StoreTypeListViewAdapter(ModifyTerminalInfoActivity.this, (ArrayList<String>) shopNames);

        listview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        listview.setAdapter(adapters);
        builder.setContentView(view);
        tvShopType.setClickable(true);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvShopType.setText(shopNames.get(position));
                request.setTerminalTypeCode(shopCodes.get(position).getCodeId());

                if (dialog != null) {
                    dialog.dismiss();

                }
            }
        });

        // 创建对话框并显示
        if (dialog == null) {
            dialog = builder.create();
        }
        dialog.show();
    }

    /**
     * 检查提交表格
     */
    private void checkForm() {
        // 终端店名称
        if (!etShopName.getText().toString().equals(request.getTerminalName())) {
            if (TextUtils.isEmpty(etShopName.getText())) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, R.string.register_store_name_msg);
                return;
            } else if (etShopName.getText().length() > 30) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, "商店名称30字以内");
                return;
            } else if (!CommonUtils.isValidTerminalName(etShopName.getText().toString())) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, getResources().getString(R.string.register_store_invalid_msg));
                return;
            } else {
                request.setTerminalName(etShopName.getText().toString().trim());
            }
        }

        // 营业执照号
        if (!etBusinessLicense.getText().toString().equals(request.getBusinessLicenseCode())) {
            if (TextUtils.isEmpty(etBusinessLicense.getText())) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, R.string.store_business_license_msg);
                return;
            } else if (etBusinessLicense.getText().length() > 30) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, "营业执照号30字以内");
                return;
            } else {
                request.setBusinessLicenseCode(etBusinessLicense.getText().toString().trim());
            }
        }

        // 终端店详细地址
        if (!etShopDetail.getText().toString().equals(request.getTerminalDetailAddress())) {
            if (TextUtils.isEmpty(etShopDetail.getText())) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, R.string.register_store_detail_add_msg);
                return;
            } else if (etShopDetail.getText().length() > 140) {
                ToastUtils.showShort(ModifyTerminalInfoActivity.this, "详细地址140字以内");
            } else {
                request.setTerminalDetailAddress(etShopDetail.getText().toString().trim());
            }
        }
        agent.getApi()
                .modifyTerminalInfo(request)
                .compose(OperatorUtils.<TerminalInformationModifyResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<TerminalInformationModifyResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(TerminalInformationModifyResponse terminalInformationModifyResponse) {
                        toPrevious();
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "修改失败" : displayMessage);
                    }
                });
    }
}